package com.android.dumiaogou.fragment.member;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.activity.BaseObject;
import com.android.dumiaogou.activity.DirectBuyPayOrderActivity;
import com.android.dumiaogou.adapt.listMineDirectBuyOrderAdapt;
import com.android.dumiaogou.fragment.BaseLazyFragment;
import com.android.dumiaogou.model.data;
import com.android.dumiaogou.model.dataCallback;
import com.android.dumiaogou.model.member.DirectBuyOrderList;
import com.android.dumiaogou.model.member.DirectBuyOrderListCallback;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.dialog.MainMsg;
import com.android.dumiaogou.view.recycleview.CustomLoadMoreView;
import com.android.dumiaogou.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 直购订单列表
 * ---------------------------------------
 */
public class Fragment_Mine_DirectBuy_Order extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.top)
    ImageView top;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_auction_record)
    LinearLayout noRecord;

    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private View rootView;
    private static final String ARG_PARAM1 = "param1";

    private String mParam1;
    private listMineDirectBuyOrderAdapt adapter;

    private int page = 1;
    private boolean networkConnected;
    private FragmentActivity mcontext;

    public static String DIRECTBUY_ORDER_PAY = "directbuy_order_pay";
    public static String DIRECTBUY_ORDER_SHOUHUO = "directbuy_order_shouhuo";
    public static String DIRECTBUY_ORDER_COMMENT = "directbuy_order_comment";
    private boolean isInit = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
        registerReceiver();
    }

    public static Fragment_Mine_DirectBuy_Order newInstance(String param1) {
        Fragment_Mine_DirectBuy_Order fragment = new Fragment_Mine_DirectBuy_Order();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);

        fragment.setArguments(args);
        return fragment;
    }

    private void initUI() {
        adapter = new listMineDirectBuyOrderAdapt(R.layout.item_list_mine_directbuy_order, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop(top, 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, BaseObject.class);
                intent.putExtra("title", "订单详情");
                intent.putExtra("need_id", adapter.getItem(position).getOrder_sn());
                intent.putExtra("type", 1);
                mcontext.startActivity(intent);
            }
        });

        adapter.setOnItemChildClickListener(itemChildClickListener);
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    @Override
    protected void onInvisible() {
    }

    @Override
    protected void initData() {
        isInit = true;
        page = 1;
        mRecyclerView.scrollToPosition(0);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            GetDataListData(page, mParam1);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    private void registerReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(DIRECTBUY_ORDER_PAY);
        myIntentFilter.addAction(DIRECTBUY_ORDER_SHOUHUO);
        myIntentFilter.addAction(DIRECTBUY_ORDER_COMMENT);
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.fragment_mine_directbuy_order, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initUI();
        return rootView;
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            //设置颜色
            mRefreshLayout.setColorSchemeResources(R.color.app_title);
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    {
                        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
                        if (networkConnected) {
                            page = 1;
                            GetDataListData(page, mParam1);
                        } else {
                            ObjectUtils.toast(getActivity(), "网络连接出现异常");
                            mRefreshLayout.setRefreshing(false);
                        }
                    }
                }
            });
        }
    }

    //获取列表数据
    private void GetDataListData(final int page, String type) {
        String address;
        if (type.equals("0")) {
            address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDER + "?page=" + page;
        } else {
            address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDER + "?page=" + page + "&status=" + type;
        }

        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, listCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
            mRefreshLayout.setRefreshing(false);
        }
    }

    DirectBuyOrderListCallback listCallback = new DirectBuyOrderListCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            } else {
                ObjectUtils.toast(mcontext, "网络连接出现异常");
                adapter.loadMoreFail();
            }
            mRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onResponse(DirectBuyOrderList response, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            mRefreshLayout.setRefreshing(false);
            if (response.getCode() == 0) {
                ArrayList<DirectBuyOrderList.DataBean.ListBean> listdata = new ArrayList<>();
                if (response.getData() == null && page == 1) {
                    noRecord.setVisibility(View.VISIBLE);
                    return;
                }
                noRecord.setVisibility(View.GONE);
                if (response.getData() != null && response.getData().getList().size() > 0) {
                    listdata.addAll(response.getData().getList());
                    if (page == 1) {
                        adapter.setNewData(listdata);
                    } else {
                        adapter.addData(listdata);
                        adapter.loadMoreComplete();
                    }
                } else {
                    if (page == 1) {
                        noRecord.setVisibility(View.VISIBLE);
                    }
                    adapter.loadMoreEnd();
                }
            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
                if (page == 1) {
                    noData.setVisibility(View.VISIBLE);
                    noDataTv.setText(response.getMsg());
                    noDataTv.setVisibility(View.VISIBLE);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    adapter.loadMoreFail();
                }
            }
        }
    };

    @OnClick({R.id.click_resetnetwork_refresh, R.id.no_auction_record
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.click_resetnetwork_refresh:
                initGetData();
                break;
            case R.id.no_auction_record:
                Intent intent_address = new Intent(mcontext, BaseObject.class);
                intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "大市场");
                startActivity(intent_address);
                break;
        }
    }

    private void initGetData() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        GetDataListData(page, mParam1);
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page, mParam1);
    }

    BaseQuickAdapter.OnItemChildClickListener itemChildClickListener = new BaseQuickAdapter.OnItemChildClickListener() {
        @Override
        public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, final int position) {
            final MainMsg mainMsg;
            switch (view.getId()) {
                case R.id.daifukuang_pay:
                    Intent intent_pay = new Intent(mcontext, DirectBuyPayOrderActivity.class);
                    intent_pay.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ORDER_ID, adapter.getItem(position).getOrder_sn());
                    startActivity(intent_pay);
                    break;
                case R.id.daishouhuo_wuliu:
                    Intent intent_express = new Intent(mcontext, BaseObject.class);
                    intent_express.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "物流详情");
                    intent_express.putExtra("need_id", adapter.getItem(position).getOrder_sn());
                    startActivity(intent_express);
                    break;
                case R.id.daishouhuo_queren:
                    mainMsg = new MainMsg(mcontext);
                    mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否确认收到货物？");
                    mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                        @Override
                        public void onSure() {
                            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDERQUERENSHOUHUO + "?id=" + adapter.getItem(position).getId();
                            getData(address, position);
                            mainMsg.close();
                        }
                    });
                    break;
                case R.id.daipinjia_pinjia:
                    Intent intent_rate = new Intent(mcontext, BaseObject.class);
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "评价");
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_GOOD_ID, adapter.getItem(position).getGoods_item().get(0).getGood_id());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_ID, adapter.getItem(position).getId());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_BUY_NUM, adapter.getItem(position).getGoods_item().get(0).getBuy_num());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_THUMB, adapter.getItem(position).getGoods_item().get(0).getThumb());
                    startActivity(intent_rate);
                    break;
//                case R.id.daifukuang_canceldingdang:
//                    mainMsg = new MainMsg(mcontext);
//                    mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否取消订单？");
//                    mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
//                        @Override
//                        public void onSure() {
//                            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDERCANCEL + "?id=" + adapter.getItem(position).getId();
//                            getData(address, position);
//                            mainMsg.close();
//                        }
//                    });
//                    break;
            }
            return false;
        }
    };

    private void getData(String url, final int position) {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
        HttpUtils.get(url, header, null, new dataCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                progress.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, "网络连接出现异常");
            }

            @Override
            public void onResponse(data response, int id) {
                progress.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, response.getMsg());
                if (response.getCode() == 0) {
                    Intent mIntent = new Intent(DIRECTBUY_ORDER_SHOUHUO);
                    mcontext.sendBroadcast(mIntent);
                }
            }
        });
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(!isInit) return;
            String action = intent.getAction();
            if (mParam1.equals("0")) {
                initGetData();
            }else{
                if(action.equals(DIRECTBUY_ORDER_PAY)){
                    if(mParam1.equals("100") || mParam1.equals("101")){
                        initGetData();
                    }
                }else if(action.equals(DIRECTBUY_ORDER_SHOUHUO)){
                    if(mParam1.equals("102") || mParam1.equals("110")){
                        initGetData();
                    }
                }else if(action.equals(DIRECTBUY_ORDER_COMMENT)){
                    if(mParam1.equals("110")){
                        initGetData();
                    }
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
        mBroadcastReceiver = null;
    }
}
